package com.itjiange.interceptor;

import com.itjiange.constant.UserConstant;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录拦截器
 *
 * @author ItJiange
 * @date 2023/10/31
 */
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info(requestURI);
        // 获取 session 对象
        HttpSession requestSession = request.getSession();
        Object userStatus = requestSession.getAttribute(UserConstant.USER_STATUS);
        // 用户未登录时，不允许访问其他资源
        if (userStatus == null) {
            response.sendRedirect("http://localhost:7070/login.html");
            log.info("用户未登录，请求转发！！！");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
    }
}
